package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 李先生
 */
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    //查询全部
    @GetMapping
    public Result findAllBooks(){
        List<Book> book = bookService.findAllBooks();
        Integer code = book != null ? Code.findAllBooks_OK : Code.findAllBooks_NO;
        String msg = book != null ? "查询成功" : "查询失败";
        return new Result(code,book,msg);
    }
    //查询id
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id){
        if (id == 1){
            int i = 1/0;
        }else if(id==2) {
            throw new BusinessException(Code.BUSINESS_ERR1,"请不要用你的技术挑战我的耐心");
        }else if (id==3){
            throw new SystemException(Code.SYSTEM_ERR,"网络堵塞，请稍后再试~");
        }
        Book byId = bookService.findById(id);
        Integer code = byId != null ? Code.findById_OK : Code.findById_NO;
        String msg = byId != null ? "查询成功" : "数据失败";
        return new Result(code,byId,msg);
    }

    //增加
    @PostMapping
    public Result saveBooks(@RequestBody Book book){
        boolean saveBooks = bookService.saveBooks(book);
        return new Result(saveBooks? Code.saveBooks_OK:Code.saveBooks_NO,saveBooks,"添加成功");
    }
    //修改
    @PutMapping
    public Result updateBooks(@RequestBody Book book){
        boolean updateBooks = bookService.updateBooks(book);
        return new Result(updateBooks? Code.updateBooks_OK:Code.updateBooks_NO,updateBooks,"修改成功");
    }
    //删除
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        boolean deleteById = bookService.deleteById(id);
        return new Result(deleteById? Code.deleteById_OK:Code.deleteById_NO,deleteById,"删除成功");
    }
}
